package com.xyzq.cgate.core.filter.concrete;

import com.alibaba.fastjson.JSON;
import com.xyzq.cgate.common.constant.Constants;
import com.xyzq.cgate.common.rule.custom.entity.MatchCondition;
import com.xyzq.cgate.core.filter.AbstractFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import java.util.Objects;

/**
 * @Description:
 * @author chenchen
 * @date 2019/6/19 15:28
 */
public class ParamVerifyFilter extends AbstractFilter {

    @Override
    protected Mono<Boolean> doFilter(ServerWebExchange exchange, WebFilterChain chain) {
        final ServerHttpRequest request = exchange.getRequest();
        MatchCondition requestMatchCondition = MatchCondition.transform(request);
        if (verify(requestMatchCondition, exchange)) {
            exchange.getAttributes().put(Constants.REQUESTDTO, requestMatchCondition);
        } else {
            return Mono.just(false);
        }
        return Mono.just(true);
    }

    private boolean verify(MatchCondition requestMatchCondition, ServerWebExchange exchange) {
        if (Objects.isNull(requestMatchCondition)
                || StringUtils.isBlank(requestMatchCondition.getModule())
                || StringUtils.isBlank(requestMatchCondition.getMethod())) {
            return false;
        }
        return true;
    }

    @Override
    protected Mono<Void> doDenyResponse(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.BAD_REQUEST);
        return response.writeWith(Mono.just(response.bufferFactory()
                .wrap(JSON.toJSONString(HttpStatus.BAD_REQUEST.getReasonPhrase()).getBytes())));
    }
}
